const db = require("./libs/DBhelper");
const fs = require("./libs/FileHelper");

const express = require("express");
const moment = require("moment");
const cors = require('cors');
const svgCaptcha = require('svg-captcha');

let server = express();

//静态资源
server.use(express.static("./../src/"));


server.use(cors()) //解决跨域问题
server.use(express.urlencoded({
    extended: false
}));
server.use(express.json());


// 验证码
server.get("/api/yzm", function (request, response, next) {
    const codeConfig = {
        size: 4, // 验证码长度
        ignoreChars: '0oO1ilI', // 验证码字符中排除 0oO1ilI
        noise: (2 + parseInt(Math.random() * 8)), // 干扰线条的数量
        width: 80,
        height: 20,
        fontSize: 20,
        color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
        background: '#eee',
    };
    const captcha = svgCaptcha.create(codeConfig);
    // console.log(captcha);
    captcha.text = captcha.text.toLowerCase();
    response.json(captcha)
})


//post 注册
// name, pwd, sex, nikename, datetime
server.post("/api/reg", async (request, response, next) => {
    let params = [
        request.body.uname,
        request.body.upwd,
        request.body.uphone,
    ]

    let sql = "INSERT INTO `userinfo`(`uname`,`upwd`,`uphone`) VALUE (?,?,?);";

    try {
        let res = await db.exec(sql, params);
        //插入,删除,修改,返回 受影响行数
        let resFlag = (res && res.affectedRows >= 1);
        let oMsg = {
            message: resFlag ? "注册成功!" : "注册失败",
            code: resFlag ? 200 : -200
        }
        response.json(oMsg);
    } catch (error) {
        response.json({
            message: "注册失败",
            err: error.message,
            code: -201
        });
    }
})

//post 登录
server.post("/api/login", async (request, response, next) => {
    let params = [
        request.body.uname,
        request.body.upwd
    ];

    let sql = "SELECT `uId`,`uname`,`uphone` FROM `userinfo` WHERE `uname`=? AND `upwd`=? AND `ustatus`=1;";

    try {
        let res = await db.exec(sql, params);
        let flag = (res && res.length >= 1);
        let oMsg = {
            message: flag ? "登录成功" : "登录失败",
            code: flag ? 200 : -200,
        }
        flag ? oMsg["data"] = res[0] : "";
        response.json(oMsg)
    } catch (error) {
        response.json({
            message: "登录失败",
            err: error.message,
            code: 201
        })
    }

})

//获取所有的商品
server.get("/api/prods", async (request, response, next) => {
    let data = JSON.parse(await fs.getFile("./data/production.json"));
    console.log(data);
    response.json({
        msg: "查询成功",
        code: 200,
        data
    });
})

//根据产品id,获取到产品的详细信息
// 如果路由的路径是 /:id ,要取得id对应的值,使用 param (Vue)
// 动态路由传参
server.get("/api/prodInfo/:id", async (request, response, next) => {
    let id = request.params.id;
    let data = JSON.parse(await fs.getFile("./data/production.json"));
    let res = data.find(el => el.pid == id);
    console.log(data);
    response.json({
        msg: "查询成功",
        code: 200,
        data: res
    });
})

//加入购物车
server.post("/api/AddCarts", async (request, response, next) => {
    let params = [
        request.body.uId,
        request.body.pname,
    ]
    let querySql = "SELECT * FROM `carts` WHERE uId=? AND pName=? AND `cStatus`=1;";
    let res = await db.exec(querySql, params);

    console.log(res);
    let status = (res && res.length >= 1); //有 -> true
    if (status) {
        //修改
        let paramsUpdate = [
            request.body.pnum,
            request.body.uId,
            request.body.pname
        ]
        let updateSQL = 'UPDATE `carts` SET `pNumber`=pNumber+? ,pTotal= pNumber*pPrice WHERE uId=? AND pName=? AND `cStatus`=1;'

        let res = await db.exec(updateSQL, paramsUpdate);
        //更新,删除,修改,返回受影响行数pTotal
        let status = (res && res.affectedRows >= 1); //修改成功

        response.json({
            message: status ? "加入购物车成功!u" : "加入购车失败u",
            code: 200
        })
    } else {
        //插入
        let params = [
            request.body.uId,
            request.body.pname,
            request.body.ptype,
            request.body.pprice,
            request.body.ptime,
            request.body.pnum,
            request.body.pprice * request.body.pnum,
            request.body.pimg,
            moment().format("YYYY-MM-DD HH:mm:ss"),
            request.body.gamename
        ];
        let insertSQL = "INSERT INTO `carts` (`uId`,`pName`,`pType`,`pPrice`,`pTime`,`pNumber`,`pTotal`,`cImg`,`cTime`,`gemaname`)VALUES(?,?,?,?,?,?,?,?,?,?);";
        console.log(params);
        let res = await db.exec(insertSQL, params);
        let status = (res && res.affectedRows >= 1); //插入成功 true

        response.json({
            message: status ? "加入购物车成功!i" : "加入购车失败i",
            code: 200
        })
    }
})
//查询购物车
server.get("/api/cartList", async (request, response, next) => {

    let params = [
        request.query.uId
    ]

    let sql = "SELECT *FROM `carts` WHERE `cStatus` =1 AND `uId`=?;";
    let res = await db.exec(sql, params);

    response.json({
        message: "查询成功",
        data: res
    })

})
// 购物车的id, 购买的数量 ,ajax发送  pnum和cid过来
server.post("/api/modify", async (request, response, next) => {
    let params = [
        request.body.pnum,
        request.body.cid,
    ]
    let sql = "UPDATE `carts` SET `pNumber`= ?,`pTotal`=`pNumber`*`pPrice` WHERE `cId`=?;";

    let res = await db.exec(sql, params);
    //因为修改,关注 受影响行数
    let status = (res && res.affectedRows >= 1); //true

    response.json({
        message: status ? "修改数量成功" : "修改数量失败",
        code: 200
    });

})

//删除购物车 post  cid
server.post("/api/delete", async (request, response, next) => {
    let params = [
        request.body.cid,
    ]
    let sql = "UPDATE carts SET `cStatus`=0 WHERE cid=?;";

    let res = await db.exec(sql, params);
    //因为修改,关注 受影响行数
    let status = (res && res.affectedRows >= 1); //true

    response.json({
        message: status ? "删除成功" : "删除失败",
        code: 200
    });

})
server.listen(8080, () => {
    console.log("服务器启动完毕!");
})